package com.elite.groovy.service;

import com.elite.groovy.callback.GroovyProcess;
import com.elite.groovy.callback.ServiceBackInvoke;
import com.elite.groovy.util.EliteBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ProcessServiceRequire implements InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(ProcessServiceRequire.class);
    @Autowired
    private GroovyProcess groovyProcess;
    @Autowired
    private EliteBean eliteBean;

    public ProcessServiceRequire() {
    }

    public void doOldGeneralService(String method, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        ServiceBackInvoke invokeGroovy = (ServiceBackInvoke)this.groovyProcess.getGroovyClass(method).newInstance();
        String result = invokeGroovy.doCallBack(this.eliteBean, request, response);
        PrintWriter out = response.getWriter();
        out.print(result);
    }

    public void doDbGroovyScriptService(String method, String groovyContent, long modifyDateLong, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        log.debug("groovyClass start {}", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
        Class<ServiceBackInvoke> groovyClass = this.groovyProcess.getGroovyClass(method, groovyContent, modifyDateLong);
        log.debug("groovyClass end {}", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
        ServiceBackInvoke invokeGroovy = (ServiceBackInvoke)groovyClass.newInstance();
        log.debug("result start {}", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
        String result = invokeGroovy.doCallBack(this.eliteBean, request, response);
        log.debug("result end {}", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
        PrintWriter out = response.getWriter();
        out.print(result);
    }

    public void afterPropertiesSet() throws Exception {
        List<Map<String, Object>> groovyList = this.eliteBean.listAllGroovyScripts();
        this.groovyProcess.deployAllGroovyScript(groovyList);
    }
}
